package com.demo.sender.notice.slack;

import com.alibaba.fastjson2.JSON;
import com.demo.common.ResultData;
import com.demo.request.NoticeBaseReq;
import com.demo.sender.notice.NoticeSenderService;
import com.demo.sender.notice.slack.enums.SlackTypeEnum;
import com.demo.sender.notice.slack.request.SlackMessageReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 文档地址：<a href="https://core.telegram.org/bots/api">https://core.telegram.org/bots/api</a>
 *
 * @author wangfengchen
 */
@Slf4j
@Component
public class SlackSender implements NoticeSenderService {


  @Autowired
  private RestTemplate restTemplate;


  @Override
  public ResultData<Object> send(NoticeBaseReq req) {
    SlackTypeEnum typeEnum = SlackTypeEnum.match(req.getMsgType());
    if (ObjectUtils.isEmpty(typeEnum)) {
      return ResultData.fail("消息类型错误");
    }
    SlackMessageReq slackMessageReq = new SlackMessageReq();
    slackMessageReq.setText(req.getContent());
    return send(req.getWebhook(), slackMessageReq);
  }

  /**
   * 消息发送
   *
   * @param webhook
   * @param req
   * @return
   */
  private ResultData<Object> send(String webhook, SlackMessageReq req) {
    String botUrl = "https://hooks.slack.com/services/%s";
    String url = String.format(botUrl, webhook);
    log.info("slack消息发送，url = {}，request = {}", url, JSON.toJSONString(req));
    ResponseEntity<String> respEntity = this.restTemplate.postForEntity(url, req, String.class);
    log.info("slack消息发送，respEntity = {}", JSON.toJSONString(respEntity));
    if (ObjectUtils.isEmpty(respEntity)) {
      log.warn("slack消息发送失败");
      return ResultData.fail(501, "slack消息发送异常,直接返回");
    }
    if (respEntity.getStatusCode().value() != HttpStatus.OK.value() || respEntity.getBody() == null) {
      return ResultData.fail(respEntity.getStatusCodeValue(), respEntity.toString());
    }
    String result = respEntity.getBody();
    log.info("result = {} ", result);
    return ResultData.success(result);
  }


}
